var app = getApp();
var ux = require('../../../../lib/ux.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    openSettingBtnHidden:false,
    current:0,
    winH:0,
		winW:0,
    list:[],
    qrcode:"",
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.hideShareMenu();
    self=this;
    wx.getSystemInfo({
      success: function (res) {
        self.setData({
          qrcode:wx.getStorageSync("qrcode"),
          winH:res.windowHeight,
          winW:res.windowWidth,
        })
      }
    });

    var self=this;
    var banrdid=wx.getStorageSync('banrdId');
    ux.request("/api/Merchant/getPosterImgs.do", {banrd:parseInt(banrdid)},function(data){
      console.log(JSON.stringify(data.data.list))
      if(data.data.list){
        self.setData({
          list:data.data.list
        })
      }
    });
  },
  changeImgs:function(e){
    this.setData({
      current:e.detail.current
    })
  },
  preventTouchMoveTy:function(){
    return false;
},
toast: function (params) {
  if (typeof (params) == "string") {
    params = { content: params };
  }
  this.setData({
    toast: params.content
  });
  var THIS = this;
  setTimeout(function () {
    THIS.setData({
      toast: false
    });
    if (params.complete) {
      params.complete();
    }
  }, params.time || 3000);
},
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  savaImageToPhoto: function () {
      var img=this.data.list[this.data.current].tbpiPicture;
      var self=this;
    wx.getImageInfo({
      src: img,    //请求的网络图片路径
      success: function (res) {
        self.addImage(res.path);
      }
    })
  },
  addImage:function(img){
    wx.showLoading({
      title: '处理中...',
      mask:true
    })
    var obj=this.data.obj;
    var that = this;
    that.setData({
      shareShow: true,
    })
    //y方向的偏移量，因为是从上往下绘制的，所以y一直向下偏移，不断增大。
    var ctx = wx.createCanvasContext('shareCanvas')
    //店铺图片
    ctx.drawImage(img, 0,0, this.data.winW, this.data.winH-100);
    //绘制第一段文本
    var text = this.data.list[this.data.current].tbpiWz;
    var count = parseInt(text.length / 12);
    if (text.length % 12 > 0) {
      count + 1;
    }
    console.log("count"+count)
    var thenht = 0;
    if (count == 5) {
      thenht = 0;
    } else if (count == 4) {
      thenht = 0;
    } else if (count == 3) {
      thenht = 10;
    } else if (count == 2) {
      thenht = 20;
    } else if (count == 1) {
      thenht = 30;
    } else if (count == 0) {
      thenht = 40;
    }
    console.log(thenht)
    that.drawText(ctx, text, 95, this.data.winH-200+thenht, 20, 14);
    //绘制二维码
    ctx.drawImage(this.data.qrcode, 10,this.data.winH-212, 80, 80)
    ctx.draw();
    //绘制之后加一个延时去生成图片，如果直接生成可能没有绘制完成，导出图片会有问题。
    setTimeout(function () {
      wx.canvasToTempFilePath({
        x: 0,
        y: 0,
        width: that.data.winW,
        height: that.data.winH-100,
        destWidth: that.data.winW*2,
        destHeight: (that.data.winH-100)*2,
        canvasId: 'shareCanvas',
        success: function (res) {
          that.setData({
            shareImage: res.tempFilePath,
          })
          wx.saveImageToPhotosAlbum({
            filePath: that.data.shareImage,
            success: function (res) {
              that.toast("保存成功");
            },
            fail: function (res) {
              that.toast("保存失败");
            }
          })
          wx.hideLoading();
        },
        fail: function (res) {
          console.log(res)
          wx.hideLoading();
        }
      })
    }, 500);
  },
   /**
   * 绘制多行文本
   * @param ctx canvas对象
   * @param str 文本
   * @param leftWidth 距离左侧的距离
   * @param initHeight 距离顶部的距离
   * @param titleHeight 文本的高度
   * @param canvasWidth 文本的宽度
   * @returns {*}
   */
  drawText: function (ctx, str, leftWidth, initHeight, titleHeight, canvasWidth) {
    console.log(ctx, str, leftWidth, initHeight, titleHeight, canvasWidth)
    let lastSubStrIndex = 0; //每次开始截取的字符串的索引
    for (let i = 0; i < str.length; i++) {
      if ((i + 1) % canvasWidth == 0) {
        ctx.setFillStyle('#ffffff')
        ctx.setFontSize(14)
        // 字符间距设置
        ctx.setTextAlign('left')
        ctx.fillText(str.substring(lastSubStrIndex, i + 1), leftWidth, initHeight); //绘制截取部分
        initHeight += titleHeight; //22为 文字大小20 + 2
        lastSubStrIndex = i + 1;
      } else if (i == str.length - 1) { //绘制剩余部分
        ctx.setFillStyle('#ffffff')
        ctx.setFontSize(14)
        ctx.setTextAlign('left')
        ctx.fillText(str.substring(lastSubStrIndex, i + 1), leftWidth, initHeight);
      }
    }
  },
  saveImg:function(){
    var that = this;
    //获取相册授权
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success() {//这里是用户同意授权后的回调
              that.savaImageToPhoto();
            },
            fail() {//这里是用户拒绝授权后的回调
              that.toast("请授权相册");
              that.setData({
                openSettingBtnHidden: true
              })
            }
          })
        } else {//用户已经授权过了
          that.savaImageToPhoto();
        }
      }
    })
  },
  cancelAuth: function () {
    var that = this;
    that.setData({
      openSettingBtnHidden: false
    })
  },
  handleSetting: function (e) {
    var that = this;
    // 对用户的设置进行判断，如果没有授权，即使用户返回到保存页面，显示的也是“去授权”按钮；同意授权之后才显示保存按钮
    if (!e.detail.authSetting['scope.writePhotosAlbum']) {
      that.toast("若不打开授权，则无法将图片保存在相册中！");
    } else {
      that.toast("授权成功");
      that.setData({
        openSettingBtnHidden: false
      })
    }
  },
})